﻿/*
 * EmeCoder v1.2.1.168
 * 作者：Administrator/PC4APPLE
 * 时间：2013-06-05 15:35:06
 * 版权：版权所有 (C) Eme Development Team 2013
*/

﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml.Serialization;
using HmFramework;
using HmFramework.Data;
using HmFramework.Log;

namespace CuteSprite.Eme.Data.CRM
{
	/// <summary>快件状态</summary>
	[Serializable]
	[ModelCheckMode(ModelCheckModes.CheckTableWhenFirstUse)]
	public class ExpressStatus : ExpressStatus<ExpressStatus> { }

	/// <summary>快件状态</summary>
	public partial class ExpressStatus<TEntity> : Entity<TEntity> where TEntity : ExpressStatus<TEntity>, new()
	{
		#region 对象操作﻿

		static ExpressStatus()
		{
			// 用于引发基类的静态构造函数，所有层次的泛型实体类都应该有一个
			TEntity entity = new TEntity();
		}

		/// <summary>验证数据，通过抛出异常的方式提示验证失败。</summary>
		/// <param name="isNew"></param>
		public override void Valid(Boolean isNew)
		{
			// 这里验证参数范围，建议抛出参数异常，指定参数名，前端用户界面可以捕获参数异常并聚焦到对应的参数输入框
			if (CWBNo.IsNullOrWhiteSpace()) throw new ArgumentNullException(__.CWBNo, _.CWBNo.DisplayName + "无效，运单号码不允许为空！");
			if (isNew)
			{
				var express = ExpressMix.FindByCWBNo(CWBNo);
				if (null == express)
				{
					throw new ArgumentOutOfRangeException(__.CWBNo, _.CWBNo.DisplayName + "无效，未知的运单号码！");
				}
				else
				{
					if ("富力同城" == express.ExpressType && "已签收" == OperationStatus && OperationStaffID <= 0)
					{
						throw new ArgumentOutOfRangeException(__.OperationStaffID, _.OperationStaffID.DisplayName + "无效，未知的派件人！");
					}
				}
			}

			// 建议先调用基类方法，基类方法会对唯一索引的数据进行验证
			base.Valid(isNew);

			if (isNew)
			{
				//if (!Dirtys[__.CreateOn]) { CreateOn = DateTime.Now; }
				CreateOn = DateTime.Now;
			}
			else if (HasDirty)
			{
				//if (!Dirtys[__.ModifiedOn]) { ModifiedOn = DateTime.Now; }
				ModifiedOn = DateTime.Now;
			}
		}

		/// <summary>已重载，插入数据</summary>
		/// <returns></returns>
		protected override int OnInsert()
		{
			if (EntityHelper.IsORMRemoting) { return base.OnInsert(); }

			if (ExpressMixID < 1)
			{
				var express = ExpressMix.FindByCWBNo(CWBNo);
				if (express != null)
				{
					ExpressMixID = express.ID;
					ExpressType = express.ExpressType;
					//CWBNo = express.CWBNo;
					OriginNo = express.OriginNo;
					OrganizeID = express.OrganizeID;
					CustomerID = express.CustomerID;
				}
			}

			if ("已揽件" == OperationStatus && (OperationOrganizeID < 1 || OperationStaffID < 1))
			{
				ExpressMix express = null;
				if (ExpressMixID > 0) { express = ExpressMix.FindByID(ExpressMixID); }
				if (express == null && !CWBNo.IsNullOrWhiteSpace()) { express = ExpressMix.FindByCWBNo(CWBNo); }
				if (express != null)
				{
					var recs = express.ExpressMixRecipients;
					if (recs != null && recs.Count > 0)
					{
						var rec = recs[0];
						OperationOrganizeID = rec.OrganizeID;
						OperationStaffID = rec.StaffID;
					}
				}
			}

			if ("转运中" == OperationStatus)
			{
				// 新增时判断是否为空，填充默认值
				if (Description.IsNullOrWhiteSpace()) { Description = "快件内部转运中"; }
			}

			if ("派送中" == OperationStatus)
			{
				// 新增时判断是否为空，填充默认值
				if (Description.IsNullOrWhiteSpace()) { Description = "快件已安排派送"; }

				ExpressMix express = null;
				if (ExpressMixID > 0) { express = ExpressMix.FindByID(ExpressMixID); }
				if (express == null && !CWBNo.IsNullOrWhiteSpace()) { express = ExpressMix.FindByCWBNo(CWBNo); }
				if (express != null && (OperationOrganizeID < 1 || OperationStaffID < 1))
				{
					OperationOrganizeID = express.SendingPiecesOrganizeID;
					var sends = express.ExpressMixSends;
					if (sends != null && sends.Count > 0)
					{
						var send = sends[0];
						if (OperationOrganizeID < 1) { OperationOrganizeID = send.OrganizeID; }
						OperationStaffID = send.StaffID;
					}
				}
			}

			if ("已签收" == OperationStatus)
			{
				ExpressMix express = null;
				if (ExpressMixID > 0) { express = ExpressMix.FindByID(ExpressMixID); }
				if (express == null && !CWBNo.IsNullOrWhiteSpace()) { express = ExpressMix.FindByCWBNo(CWBNo); }
				if (express != null)
				{
					// 新建已签收快件状态记录，同步更新派件人员信息
					if (OperationOrganizeID <= 0 && OperationStaffID > 0)
					{
						var eop = ManageProvider.Provider.StaffFactory;
						var staff = eop.FindByKey(OperationStaffID) as IStaff;
						if (staff != null)
						{
							OperationOrganizeID = staff.OrganizeID;
							if (express != null)
							{
								//// 同时更新运单的派件部门
								//express.SendingPiecesOrganizeID = OperationOrganizeID;
								//express.Save();
								ExpressMixSend.GrantAll(express.ID, staff.ID.ToString(), null);
							}
						}
					}
					// 如果操作部门和操作员工都为空，自动根据富力通快件导入
					else if (OperationOrganizeID < 1 || OperationStaffID < 1)
					{
						OperationOrganizeID = express.SendingPiecesOrganizeID;
						var sends = express.ExpressMixSends;
						if (sends != null && sends.Count > 0)
						{
							var send = sends[0];
							if (OperationOrganizeID < 1) { OperationOrganizeID = send.OrganizeID; }
							OperationStaffID = send.StaffID;
						}
					}
				}

				// 如果签收人为空
				if (SignedPerson.IsNullOrWhiteSpace())
				{
					// 判断快件状态记录对应的富力通快件记录中有无签收人信息
					if (express != null && !express.SignedPerson.IsNullOrWhiteSpace())
					{
						SignedPerson = express.SignedPerson;
					}
				}
				else
				{
					// 同步对应的富力通快件中的签收人信息
					if (express != null)
					{
						express.SignedPerson = SignedPerson;
						express.Save();
					}
				}
			}

			if (!OperationStatus.Equals("已揽件"))
			{
				ExpressMix express = null;
				if (ExpressMixID > 0) { express = ExpressMix.FindByID(ExpressMixID); }
				if (express == null && !CWBNo.IsNullOrWhiteSpace()) { express = ExpressMix.FindByCWBNo(CWBNo); }
				if (express != null)
				{
					// 可能会出现先增加已签收状态，然后再增加其他状态的操作
					if (!express.OperationStatus.Equals("已签收"))
					{
						express.OperationStatus = OperationStatus;
						express.Save();
					}
				}
			}

			return base.OnInsert();
		}

		/// <summary>已重载，更新数据</summary>
		/// <returns></returns>
		protected override int OnUpdate()
		{
			if ("已签收" == OperationStatus && Dirtys[__.OperationStaffID])
			{
				var eop = ManageProvider.Provider.StaffFactory;
				var staff = eop.FindByKey(OperationStaffID) as IStaff;
				ExpressMix express = null;
				if (ExpressMixID > 0) { express = ExpressMix.FindByID(ExpressMixID); }
				if (express == null && !CWBNo.IsNullOrWhiteSpace()) { express = ExpressMix.FindByCWBNo(CWBNo); }
				if (staff != null && express != null)
				{
					OperationOrganizeID = staff.OrganizeID;
					if (express != null)
					{
						//// 同时更新运单的派件部门
						//express.SendingPiecesOrganizeID = OperationOrganizeID;
						//express.Save();
						ExpressMixSend.GrantAll(express.ID, staff.ID.ToString(), null);
					}
				}
			}

			var rs = base.OnUpdate();

			return rs;
		}

		#endregion

		#region 扩展属性﻿

		//[NonSerialized]
		//private ExpressMix _ExpressMix;
		/// <summary>该快件状态所对应的富力通快件</summary>
		[XmlIgnore]
		public ExpressMix ExpressMix
		{
			get
			{
				return Extends.GetExtend<ExpressMix, ExpressMix>("ExpressMix", e => ExpressMix.FindByID(ExpressMixID));
				//if (_ExpressMix == null && ExpressMixID > 0 && !Dirtys.ContainsKey("ExpressMix"))
				//{
				//	_ExpressMix = ExpressMix.FindByID(ExpressMixID);
				//	Dirtys["ExpressMix"] = true;
				//}
				//return _ExpressMix;
			}
			//set { _ExpressMix = value; }
			set { Extends.SetExtend<ExpressMix>("ExpressMix", value); }
		}

		#endregion

		#region 扩展查询﻿

		/// <summary>根据操作状态查找</summary>
		/// <param name="operationstatus">操作状态</param>
		/// <param name="hours"></param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static EntityList<TEntity> FindAllByOperationStatus(String operationstatus, Int32 hours = 0)
		{
			var time = DateTime.Now.AddHours(hours);
			if (Meta.Count > 1000)
			{
				var exp = _.OperationStatus.Equal(operationstatus);
				exp &= (_.IsCompleted.IsNull() | _.IsCompleted.Equal(0));
				if (hours != 0) { exp &= _.OperationTime <= time; }
				return FindAll(exp, null, null, 0, 0);
			}
			else // 实体缓存
			{
				if (hours != 0)
				{
					return Meta.Cache.Entities.FindAll(e => e.OperationStatus == operationstatus && e.IsCompleted == 0 && e.OperationTime <= time);
				}
				else
				{
					return Meta.Cache.Entities.FindAll(e => e.OperationStatus == operationstatus && e.IsCompleted == 0);
				}
			}
		}

		/// <summary>根据快件查找</summary>
		/// <param name="expressmixid">快件</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static EntityList<TEntity> FindAllByExpressMixID(Int32 expressmixid)
		{
			if (Meta.Count > 1000)
				return FindAll(_.ExpressMixID, expressmixid);
			else // 实体缓存
				return Meta.Cache.Entities.FindAll(_.ExpressMixID, expressmixid);
		}

		/// <summary>根据运单号查找</summary>
		/// <param name="cwbno">运单号</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static EntityList<TEntity> FindAllByCWBNo(String cwbno)
		{
			if (Meta.Count > 1000)
				return FindAll(_.CWBNo, cwbno);
			else // 实体缓存
				return Meta.Cache.Entities.FindAll(_.CWBNo, cwbno);
		}

		/// <summary>根据运单号、操作状态查找</summary>
		/// <param name="cwbno">运单号</param>
		/// <param name="operationstatus">操作状态</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static TEntity FindByCWBNoAndOperationStatus(String cwbno, String operationstatus)
		{
			if (Meta.Count > 1000)
				return Find(new String[] { _.CWBNo, _.OperationStatus }, new Object[] { cwbno, operationstatus });
			else // 实体缓存
				return Meta.Cache.Entities.Find(e => e.CWBNo == cwbno && e.OperationStatus == operationstatus);
		}

		/// <summary>根据所属客户、运单号查找</summary>
		/// <param name="customerid">所属客户</param>
		/// <param name="cwbno">运单号</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static EntityList<TEntity> FindAllByCWBNoAndCustomerID(Int32 customerid, String cwbno)
		{
			if (Meta.Count > 1000)
				return FindAll(new String[] { _.CustomerID, _.CWBNo }, new Object[] { customerid, cwbno });
			else // 实体缓存
				return Meta.Cache.Entities.FindAll(e => e.CustomerID == customerid && e.CWBNo == cwbno);
		}

		/// <summary>根据创建用户ID查找</summary>
		/// <param name="createuserid">创建用户ID</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static EntityList<TEntity> FindAllByCreateUserID(Int32 createuserid)
		{
			if (Meta.Count > 1000)
				return FindAll(_.CreateUserID, createuserid);
			else // 实体缓存
				return Meta.Cache.Entities.FindAll(_.CreateUserID, createuserid);
		}

		/// <summary>根据所属部门、运单号查找</summary>
		/// <param name="organizeid">所属部门</param>
		/// <param name="cwbno">运单号</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static EntityList<TEntity> FindAllByCWBNoAndOrganizeID(Int32 organizeid, String cwbno)
		{
			if (Meta.Count > 1000)
				return FindAll(new String[] { _.OrganizeID, _.CWBNo }, new Object[] { organizeid, cwbno });
			else // 实体缓存
				return Meta.Cache.Entities.FindAll(e => e.OrganizeID == organizeid && e.CWBNo == cwbno);
		}

		/// <summary>根据主键查找</summary>
		/// <param name="id">主键</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static TEntity FindByID(Int32 id)
		{
			if (Meta.Count > 1000)
				return Find(_.ID, id);
			else // 实体缓存
				return Meta.Cache.Entities.Find(_.ID, id);
			// 单对象缓存
			//return Meta.SingleCache[id];
		}

		/// <summary>根据快件查找</summary>
		/// <param name="expressmixid">快件</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static TEntity FindLastStatusByExpressMixID(Int32 expressmixid)
		{
			var es = FindAll(_.ExpressMixID.Equal(expressmixid), _.OperationTime.Desc(), null, 0, 0);
			if (es != null && es.Count > 1) { return es[0]; }
			return null;
		}

		#endregion

		#region 高级查询

		// 以下为自定义高级查询的例子

		///// <summary>
		///// 查询满足条件的记录集，分页、排序
		///// </summary>
		///// <param name="key">关键字</param>
		///// <param name="orderClause">排序，不带Order By</param>
		///// <param name="startRowIndex">开始行，0表示第一行</param>
		///// <param name="maximumRows">最大返回行数，0表示所有行</param>
		///// <returns>实体集</returns>
		//[DataObjectMethod(DataObjectMethodType.Select, true)]
		//public static EntityList<TEntity> Search(String key, String orderClause, Int32 startRowIndex, Int32 maximumRows)
		//{
		//    return FindAll(SearchWhere(key), orderClause, null, startRowIndex, maximumRows);
		//}

		///// <summary>
		///// 查询满足条件的记录总数，分页和排序无效，带参数是因为ObjectDataSource要求它跟Search统一
		///// </summary>
		///// <param name="key">关键字</param>
		///// <param name="orderClause">排序，不带Order By</param>
		///// <param name="startRowIndex">开始行，0表示第一行</param>
		///// <param name="maximumRows">最大返回行数，0表示所有行</param>
		///// <returns>记录数</returns>
		//public static Int32 SearchCount(String key, String orderClause, Int32 startRowIndex, Int32 maximumRows)
		//{
		//    return FindCount(SearchWhere(key), null, null, 0, 0);
		//}

		///// <summary>构造搜索条件</summary>
		///// <param name="key">关键字</param>
		///// <returns></returns>
		//private static String SearchWhere(String key)
		//{
		//	// WhereExpression重载&和|运算符，作为And和Or的替代
		//	// SearchWhereByKeys系列方法用于构建针对字符串字段的模糊搜索
		//	var exp = SearchWhereByKeys(key, null);

		//	// 以下仅为演示，Field（继承自FieldItem）重载了==、!=、>、<、>=、<=等运算符（第4行）
		//	//if (userid > 0) exp &= _.OperatorID == userid;
		//	//if (isSign != null) exp &= _.IsSign == isSign.Value;
		//	//if (start > DateTime.MinValue) exp &= _.OccurTime >= start;
		//	//if (end > DateTime.MinValue) exp &= _.OccurTime < end.AddDays(1).Date;

		//	return exp;
		//}

		#endregion

		#region 扩展操作

		#endregion

		#region 业务

		#region 批量更新

		#region 手动批量更新已存在状态的操作时间、操作说明

		/// <summary>批量更新已存在状态的操作时间、操作说明</summary>
		/// <param name="ids"></param>
		/// <param name="optime"></param>
		/// <param name="opDesc"></param>
		/// <param name="user"></param>
		public static void BatchUpdateStatus(String ids, String optime, String opDesc, IAdministrator user)
		{
			ValidationHelper.ArgumentNullOrEmpty(ids, "ids");

			var statusIDs = new List<Int32>(ids.SplitDefaultSeparator<Int32>());
			if (statusIDs == null) { return; }

			Meta.BeginTrans();
			try
			{
				foreach (var item in statusIDs)
				{
					var entity = FindByID(item);

					if (!optime.IsNullOrWhiteSpace())
					{
						DateTime t;
						if (DateTime.TryParse(optime, out t))
						{
							entity.OperationTime = t;
							entity.ModifiedBy = user.Name;
							entity.ModifiedUserID = user.ID;
							entity.ModifiedOn = DateTime.Now;
						}
					}
					if (!opDesc.IsNullOrWhiteSpace())
					{
						entity.Description = opDesc;
						entity.ModifiedBy = user.Name;
						entity.ModifiedUserID = user.ID;
						entity.ModifiedOn = DateTime.Now;
					}
					entity.Save();
				}

				Meta.Commit();
			}
			catch (Exception ex)
			{
				Meta.Rollback();
				throw ex;
			}
		}

		#endregion

		#region 手动批量更新快件操作状态

		/// <summary>批量更新快件操作状态</summary>
		/// <param name="os"></param>
		/// <param name="user"></param>
		public static void BatchUpdateStatus(ExpressOperationStatus os, IAdministrator user)
		{
			String srcos = null;
			String destos = null;
			String desc = null;
			Int32 hours = 0;
			switch (os)
			{
				case ExpressOperationStatus.转运中:
					srcos = "已揽件";
					destos = "转运中";
					desc = "快件内部转运中";
					hours = -3;
					break;
				case ExpressOperationStatus.派送中:
					srcos = "转运中";
					destos = "派送中";
					desc = "快件已安排派送";
					hours = -6;
					break;
				case ExpressOperationStatus.已签收:
					srcos = "派送中";
					destos = "已签收";
					desc = "收件人已签收";
					hours = -3;
					break;

				case ExpressOperationStatus.已揽件:
					srcos = "已揽件";
					hours = 1;
					break;
				case ExpressOperationStatus.已清关:
					srcos = "已清关";
					hours = 1;
					break;
				case ExpressOperationStatus.异常:
					srcos = "异常";
					hours = 1;
					break;
				default:
					break;
			}
			var time = DateTime.Now.AddHours(hours);
			if (os == ExpressOperationStatus.转运中 || os == ExpressOperationStatus.派送中 || os == ExpressOperationStatus.已签收)
			{
				// 实体缓存
				var es = FindAllByOperationStatus(srcos, hours);
				if (es == null) { return; }

				Meta.BeginTrans();
				try
				{
					foreach (var item in es)
					{
						var oldstatus = FindByCWBNoAndOperationStatus(item.CWBNo, destos);
						if (oldstatus == null)
						{
							var newstatus = item.CloneEntity(true);
							newstatus.ID = 0;
							newstatus.OperationTime = DateTime.Now;
							newstatus.OperationStatus = destos;
							newstatus.Description = desc;
							if ("转运中" == destos)
							{
								newstatus.OperationOrganizeID = 0;
								newstatus.OperationStaffID = 0;
							}
							newstatus.ModifiedBy = user.Name;
							newstatus.ModifiedOn = DateTime.Now;
							newstatus.ModifiedUserID = user.ID;
							newstatus.CreateOn = DateTime.Now;
							newstatus.CreateBy = user.Name;
							newstatus.CreateUserID = user.ID;
							newstatus.Insert();

							item.IsCompleted = 1;
							item.Update();
						}
						else
						{
							if (item.IsCompleted == 0)
							{
								item.IsCompleted = 1;
								item.Update();
							}
						}
					}
					Meta.Commit();
				}
				catch (Exception ex)
				{
					Meta.Rollback();
					throw ex;
				}
			}
		}

		#endregion

		#region 自动批量更新快件操作状态

		/// <summary>自动批量更新快件操作状态</summary>
		/// <remarks>
		/// 上午收的件基本操作就是下午会安排派送，中午12:30转运中，下午14:00派送中
		/// 下午收的件就是晚上22:30转运中，第二天早上8:30派送中
		/// 收件时间已快件的以揽件操作时间为准
		/// </remarks>
		public static void BatchUpdateStatus()
		{
			var yesterday = DateTime.Parse("{0:yyyy-MM-dd} 00:00:00".FormatWith(DateTime.Now.AddDays(-1)));
			var today = DateTime.Parse("{0:yyyy-MM-dd} 00:00:00".FormatWith(DateTime.Now));

			var timeTransport1 = DateTime.Parse("{0:yyyy-MM-dd} 12:30:00".FormatWith(DateTime.Now));
			var timeTransport2 = DateTime.Parse("{0:yyyy-MM-dd} 22:30:00".FormatWith(DateTime.Now));
			var timeTransportY = DateTime.Parse("{0:yyyy-MM-dd} 12:30:00".FormatWith(yesterday));

			#region 批量添加转运中状态

			// 先搜索没有进行转运操作的快件
			var exp = _.OperationStatus.Equal("已揽件");
			exp &= _.IsCompleted.Equal(0).Or(_.IsCompleted.IsNull());
			exp &= _.OperationTime.Between(today, today);
			var list = FindAll(exp, null, null, 0, 0);
			if (list != null && list.Count > 0)
			{
				//HmTrace.WriteLine("今天的以揽件状体有{0}条。".FormatWith(list.Count));
				Meta.BeginTrans();
				try
				{
					foreach (var item in list)
					{
						// 下午收件
						if (DateTime.Now >= timeTransport2 && item.OperationTime > timeTransport1)
						{
							// 首先判断有无手动添加转运中状态
							var newstatus = FindByCWBNoAndOperationStatus(item.CWBNo, "转运中");
							if (null == newstatus)
							{
								newstatus = item.CloneEntity(true);
								newstatus.ID = 0;
								newstatus.OperationTime = timeTransport2;
								newstatus.OperationStatus = "转运中";
								newstatus.Description = "快件内部转运中";
								newstatus.OperationOrganizeID = 0;
								newstatus.OperationStaffID = 0;
								newstatus.IsCompleted = 0;
								newstatus.ModifiedBy = "Administrator";
								newstatus.ModifiedOn = DateTime.Now;
								newstatus.ModifiedUserID = 1;
								newstatus.CreateOn = DateTime.Now;
								newstatus.CreateBy = "Administrator";
								newstatus.CreateUserID = 1;
								newstatus.Insert();
							}

							item.IsCompleted = 1;
							item.Update();
						}
						// 上午收件
						else if (DateTime.Now >= timeTransport1 && item.OperationTime <= timeTransport1)
						{
							// 首先判断有无手动添加转运中状态
							var newstatus = FindByCWBNoAndOperationStatus(item.CWBNo, "转运中");
							if (null == newstatus)
							{
								newstatus = item.CloneEntity(true);
								newstatus.ID = 0;
								newstatus.OperationTime = timeTransport1;
								newstatus.OperationStatus = "转运中";
								newstatus.Description = "快件内部转运中";
								newstatus.OperationOrganizeID = 0;
								newstatus.OperationStaffID = 0;
								newstatus.IsCompleted = 0;
								newstatus.ModifiedBy = "Administrator";
								newstatus.ModifiedOn = DateTime.Now;
								newstatus.ModifiedUserID = 1;
								newstatus.CreateOn = DateTime.Now;
								newstatus.CreateBy = "Administrator";
								newstatus.CreateUserID = 1;
								newstatus.Insert();
							}

							item.IsCompleted = 1;
							item.Update();
						}
					}

					Meta.Commit();
				}
				catch (Exception ex)
				{
					Meta.Rollback();
					throw ex;
				}
			}
			//else
			//{
			//	HmTrace.WriteLine("没有搜索到未完成的以揽件状体。");
			//}

			#endregion

			var timeSending1 = DateTime.Parse("{0:yyyy-MM-dd} 08:30:00".FormatWith(DateTime.Now));
			var timeSending2 = DateTime.Parse("{0:yyyy-MM-dd} 14:00:00".FormatWith(DateTime.Now));

			#region 批量添加派送中状态

			// 先搜索没有进行转运操作的快件
			exp = _.OperationStatus.Equal("转运中");
			exp &= _.IsCompleted.Equal(0).Or(_.IsCompleted.IsNull());
			exp &= _.OperationTime.Between(yesterday, today);
			list = FindAll(exp, null, null, 0, 0);
			if (list != null && list.Count > 0)
			{
				Meta.BeginTrans();
				try
				{
					foreach (var item in list)
					{
						// 查询相对应的已揽件状态
						var rec = FindByCWBNoAndOperationStatus(item.CWBNo, "已揽件");
						if (null == rec) { continue; }

						// 今天收件
						if (DateTime.Now >= timeSending2 && (rec.OperationTime >= today && rec.OperationTime <= timeTransport1))
						{
							// 首先判断有无手动添加派送中状态
							var newstatus = FindByCWBNoAndOperationStatus(item.CWBNo, "派送中");
							if (null == newstatus)
							{
								newstatus = item.CloneEntity(true);
								newstatus.ID = 0;
								newstatus.OperationTime = timeSending2;
								newstatus.OperationStatus = "派送中";
								newstatus.Description = "快件已安排派送";
								newstatus.OperationOrganizeID = 0;
								newstatus.OperationStaffID = 0;
								newstatus.IsCompleted = 0;
								newstatus.ModifiedBy = "Administrator";
								newstatus.ModifiedOn = DateTime.Now;
								newstatus.ModifiedUserID = 1;
								newstatus.CreateOn = DateTime.Now;
								newstatus.CreateBy = "Administrator";
								newstatus.CreateUserID = 1;
								newstatus.Insert();
							}

							item.IsCompleted = 1;
							item.Update();
						}
						// 昨天收件
						else if (DateTime.Now >= timeSending1 && (rec.OperationTime > timeTransportY && rec.OperationTime < today))
						{
							// 首先判断有无手动添加派送中状态
							var newstatus = FindByCWBNoAndOperationStatus(item.CWBNo, "派送中");
							if (null == newstatus)
							{
								newstatus = item.CloneEntity(true);
								newstatus.ID = 0;
								newstatus.OperationTime = timeSending1;
								newstatus.OperationStatus = "派送中";
								newstatus.Description = "快件已安排派送";
								newstatus.OperationOrganizeID = 0;
								newstatus.OperationStaffID = 0;
								newstatus.IsCompleted = 0;
								newstatus.ModifiedBy = "Administrator";
								newstatus.ModifiedOn = DateTime.Now;
								newstatus.ModifiedUserID = 1;
								newstatus.CreateOn = DateTime.Now;
								newstatus.CreateBy = "Administrator";
								newstatus.CreateUserID = 1;
								newstatus.Insert();
							}

							item.IsCompleted = 1;
							item.Update();
						}
					}

					Meta.Commit();
				}
				catch (Exception ex)
				{
					Meta.Rollback();
					throw ex;
				}
			}

			#endregion
		}

		#endregion

		#endregion

		#endregion
	}

	/// <summary>快件操作状态</summary>
	public enum ExpressOperationStatus : int
	{
		/// <summary>已揽件</summary>
		已揽件,

		/// <summary>转运中</summary>
		转运中,

		/// <summary>已清关</summary>
		已清关,

		/// <summary>派送中</summary>
		派送中,

		/// <summary>已签收</summary>
		已签收,

		/// <summary>异常</summary>
		异常
	}
}